package com.xiliubit.cloudpicture.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.xiliubit.cloudpicture.exception.BusinessException;
import com.xiliubit.cloudpicture.exception.ErrorCode;
import com.xiliubit.cloudpicture.exception.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class UrlPictureUpload extends PictureUploadTemplate {

//    @Resource
//    private CosManager cosManager;

    private String Suffix = null;

    /*
      上传图片

      @param urlFile           图片URL地址
     * @param uploadPathPrefix 上传路径前缀
     */
/*    public PictureUploadResult putPicture(String urlFile, String uploadPathPrefix) {
        // 校验图片
        validPicture(urlFile);
        // 图片地址
        String originalFilename = getOriginalFilename(urlFile);
        String uploadFilename = String.format("%s_%s.%s",
                LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                RandomUtil.randomString(8), Suffix);
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);

        // 文件目录
        String filepath = String.format("/test/%s", originalFilename);
        File file = null;
        try {
           // 创建临时文件
            file = File.createTempFile(filepath, null);
            processFile(urlFile, file);
            // 上传文件
            PutObjectResult putObjectResult = cosManager.putPictureObject(file, uploadPath);
            // 封装返回结果
            return buildResult(putObjectResult, originalFilename, uploadPath,file);
        } catch (Exception e) {
            log.error("文件上传失败: {}", filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            deleteTempFile(file, filepath);
        }

    }*/

    /**
     * 校验图片
     *
     * @param inputSource 源文件
     * @return 图片后缀
     */
    @Override
    public String validPicture(Object inputSource) {
        String urlFile = (String) inputSource;
        // 1.不能为空
        ThrowUtils.throwIf(StrUtil.isBlank(urlFile), ErrorCode.PARAMS_ERROR, "文件地址不能为空");
        // 2.验证Url格式
        try {
            new URL(urlFile);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件地址格式不正确");
        }
        // 3.校验URL协议
        ThrowUtils.throwIf(!urlFile.startsWith("http://") && !urlFile.startsWith("https://"),
                ErrorCode.PARAMS_ERROR, "仅支持 HTTP 或 HTTPS 协议的文件地址");

        // 发送head请求
        HttpResponse httpResponse = null;
        try {
            httpResponse = HttpUtil.createRequest(Method.HEAD, urlFile).execute();
            // 3.能收到响应
            if (httpResponse.getStatus() != HttpStatus.HTTP_OK){
                // 未正常响应，无需执行其他操作
                // 因为有些URL地址可能不支持HEAD请求访问
                return "png";
            }
            // 获取文件信息进行校验
            String contentType = httpResponse.header("Content-Type");
            if (StrUtil.isNotBlank(contentType)){
                // 4.校验后缀
                final List<String> fileSuffixList = Arrays.asList("image/png", "image/jpg", "image/jpeg", "image/webp");
                ThrowUtils.throwIf(!fileSuffixList.contains(contentType), ErrorCode.PARAMS_ERROR, "文件类型错误");
                Suffix = contentType.split("/")[1];
            }
            String contentLengthStr = httpResponse.header("Content-Length");
            // 5.大小不能超过3mb
            if (StrUtil.isNotBlank(contentLengthStr)){
                final long ONE_M = 1024 * 1024L;
                try {
                    long contentLength = Long.parseLong(contentLengthStr);
                    ThrowUtils.throwIf(contentLength > ONE_M * 3, ErrorCode.PARAMS_ERROR, "图片大小不能超过3M");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                }
            }
            return Suffix;
        } finally {
            if (httpResponse != null) {
                httpResponse.close();
            }
        }
  }

    /**
     * 获取原始文件名
     *
     * @param inputSource 源文件
     * @return 原始文件名
     */
    @Override
    public String getOriginalFilename(Object inputSource) {
        String urlFile = (String) inputSource;
        return FileUtil.getName(urlFile);
    }

    /**
     * 下载文件到本地作为中转
     *
     * @param inputSource 源文件
     * @param file 中转文件
     */
    @Override
    public void processFile(Object inputSource, File file) {
        String urlFile = (String) inputSource;
        try {
            HttpUtil.downloadFile(urlFile, file);
        } catch (Exception e) {
            log.error("文件下载失败: {}", e.getMessage(), e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
    }



}
